import hashlib
import json
from urllib.parse import urlencode, quote_plus


def createSign():
    secretKey = "fJ+8txYv+onBQSNT7JxwGA=="
    # 向我司服务器发送的JSON数据
    data = '{"imei": "123456", "command": 121, "secret_id": "secretId", "timestamp": "时间戳"}'
    # 将JSON字符串转换为URL参数格式
    urlParams = jsonToUrlParams(data) + secretKey
    # MD5加密
    return encryptToMd5(urlParams)


def encryptToMd5(str):
    md5 = hashlib.md5()
    md5.update(str.encode('utf-8'))
    return md5.hexdigest()


def jsonToUrlParams(jsonString):
    try:
        print(jsonString)
        # 解析JSON字符串
        rootNode = json.loads(jsonString)

        # 过滤非数字和字符串类型的值
        cleanedNode = {}
        for fieldName, fieldValue in rootNode.items():
            if isinstance(fieldValue, (int, float, str)):
                cleanedNode[fieldName] = fieldValue

        # 对字段名进行排序
        sortedFields = sorted(cleanedNode.items())

        # 构建URL参数
        params = urlencode(sortedFields, quote_via=quote_plus)

        return params
    except Exception as e:
        print(e)
        return str(e)
